/**
 * 测试币安集成功能脚本
 * 用于测试币安API服务和多交易所监控功能
 */

require('dotenv').config();
const path = require('path');

// 设置工作目录到项目根目录
const projectRoot = path.join(__dirname, '..');
process.chdir(projectRoot);

const BinanceApiService = require(path.join(projectRoot, 'src/services/binanceApiService'));
const ExchangeFactory = require(path.join(projectRoot, 'src/services/exchangeFactory'));
const EmailService = require(path.join(projectRoot, 'src/services/emailService'));
const logger = require(path.join(projectRoot, 'src/utils/logger'));

async function testBinanceIntegration() {
  logger.info('🧪 开始测试币安集成功能...');
  
  try {
    // 1. 测试币安API服务
    logger.info('📡 测试币安API服务...');
    const binanceService = new BinanceApiService();
    
    // 检查连接
    const connectionOk = await binanceService.checkConnection();
    if (connectionOk) {
      logger.success('✅ 币安API连接正常');
    } else {
      logger.warn('⚠️  币安API连接失败，但继续测试其他功能');
    }
    
    // 获取交易对数据
    let binancePairs = [];
    if (connectionOk) {
      try {
        logger.info('📊 获取币安交易对数据...');
        binancePairs = await binanceService.fetchTradingPairs();
        logger.success(`✅ 成功获取 ${binancePairs.length} 个币安交易对`);
        logger.info(`   示例交易对: ${binancePairs.slice(0, 10).join(', ')}...`);
      } catch (error) {
        logger.error(`❌ 获取币安交易对失败: ${error.message}`);
      }
    } else {
      logger.info('⏭️  跳过获取币安交易对数据（连接失败）');
    }
    
    // 2. 测试交易所工厂
    logger.info('🏭 测试交易所工厂...');
    const exchangeFactory = new ExchangeFactory();
    exchangeFactory.initialize(['upbit', 'binance']);
    
    const statusSummary = exchangeFactory.getStatusSummary();
    logger.info(`✅ 交易所工厂初始化完成: ${statusSummary.enabled}/${statusSummary.total} 个交易所启用`);
    
    // 检查所有连接
    logger.info('🔗 检查所有交易所连接...');
    const connectionResults = await exchangeFactory.checkAllConnections();
    for (const [exchangeId, result] of Object.entries(connectionResults)) {
      if (result.connected) {
        logger.success(`✅ ${result.name}: 连接正常`);
      } else {
        logger.error(`❌ ${result.name}: 连接失败${result.error ? ` - ${result.error}` : ''}`);
      }
    }
    
    // 3. 测试获取所有交易所数据
    logger.info('📈 测试获取所有交易所交易对数据...');
    const allTradingPairs = await exchangeFactory.fetchAllTradingPairs();
    
    for (const [exchangeId, data] of Object.entries(allTradingPairs)) {
      const exchangeName = exchangeFactory.exchanges.get(exchangeId)?.name || exchangeId;
      if (data.success) {
        logger.success(`✅ ${exchangeName}: ${data.count} 个交易对`);
      } else {
        logger.error(`❌ ${exchangeName}: ${data.error}`);
      }
    }
    
    // 4. 测试多交易所邮件格式
    logger.info('📧 测试多交易所邮件格式...');
    const emailService = new EmailService();
    
    // 创建测试数据
    const testNewPairs = [
      { pair: 'BTC-TEST1', exchange: 'upbit', exchangeName: 'Upbit' },
      { pair: 'ETH-TEST1', exchange: 'upbit', exchangeName: 'Upbit' },
      { pair: 'DOGEUSDT', exchange: 'binance', exchangeName: 'Binance' },
      { pair: 'ADAUSDT', exchange: 'binance', exchangeName: 'Binance' },
      { pair: 'DOTUSDT', exchange: 'binance', exchangeName: 'Binance' }
    ];
    
    // 测试控制台输出
    logger.info('📝 测试控制台输出格式:');
    emailService.logNewPairsToConsole(testNewPairs);
    
    // 测试邮件内容生成
    const timestamp = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    const htmlContent = emailService.generateMultiExchangeEmailHTML(testNewPairs, timestamp);
    const textContent = emailService.generateMultiExchangeEmailText(testNewPairs, timestamp);
    
    logger.info('📧 多交易所邮件内容生成成功');
    logger.info(`   HTML内容长度: ${htmlContent.length} 字符`);
    logger.info(`   文本内容长度: ${textContent.length} 字符`);
    
    // 5. 测试发送邮件（如果配置了）
    const emailConfigured = await emailService.verifyConfig();
    if (emailConfigured) {
      logger.info('📤 邮件配置正常，测试发送多交易所通知邮件...');
      await emailService.sendNewPairsNotification(testNewPairs);
      logger.success('✅ 多交易所通知邮件发送测试完成');
    } else {
      logger.warn('⚠️  邮件未配置，跳过邮件发送测试');
    }
    
    // 6. 显示配置建议
    logger.info('💡 配置建议:');
    logger.info('   1. 在 .env 文件中设置 ENABLED_EXCHANGES=upbit,binance');
    logger.info('   2. 或者只启用某个交易所: ENABLED_EXCHANGES=upbit');
    logger.info('   3. 建议检查间隔不少于3秒: CHECK_INTERVAL=3000');
    
    logger.success('🎉 币安集成功能测试完成！');
    
  } catch (error) {
    logger.error(`测试过程中出错: ${error.message}`);
    logger.error(error.stack);
  }
}

// 运行测试
testBinanceIntegration().then(() => {
  logger.info('👋 测试脚本执行完成');
  process.exit(0);
}).catch(error => {
  logger.error(`测试脚本执行失败: ${error.message}`);
  process.exit(1);
});
